﻿#nullable disable
using System;
using System.Collections.Generic;
using EFCore读写分离.DAL;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace EFCore读写分离.Models
{
    public partial class DbApplicationContext : DbContext
    {

        public DbApplicationContext(DbConnectionOptions connectionOptions,SlaveRoundRobin slaveRoundRobin,DbContextOptions<DbApplicationContext> options)
            : base(options)
        {
            _connectionOptions = connectionOptions;
            _slaveRoundRobin = slaveRoundRobin;
        }

        private DbConnectionOptions _connectionOptions;
        private SlaveRoundRobin _slaveRoundRobin;

        public virtual DbSet<DataUser> DataUsers { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
                optionsBuilder.UseMySql(_connectionOptions.MasterConnection, Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.32-mysql"));
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("utf8mb4_unicode_ci")
                .HasCharSet("utf8mb4");

            modelBuilder.Entity<DataUser>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

        public void ToMaster()
        {
            Database.GetDbConnection().ConnectionString = _connectionOptions.MasterConnection;
        }

        public void ToSlave()
        {
            Database.GetDbConnection().ConnectionString = _slaveRoundRobin.NextSlave();
        }
    }
}